package controllers

import "C"
import (
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
)

type NewsController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	time := c.GetString("time")
	types := c.GetString("types")
	news := models.News{
		Title: title,
		Time:  time,
		Types: types,
	}
	err := models.DB.Create(&news)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *NewsController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	pageData := make(map[string]interface{})
	var count int64
	err := models.DB.Model(&models.News{}).Count(&count).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "总数查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	offset := (page - 1) * size
	var news []models.News
	err = models.DB.Offset(offset).Limit(size).Find(&news).Error
	pageData["count"] = count
	pageData["news"] = news
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
func (c *NewsController) Up() {
	title := c.GetString("title")
	time := c.GetString("time")
	types := c.GetString("types")
	id, _ := c.GetInt("id")
	news := models.News{
		Title: title,
		Time:  time,
		Types: types,
	}
	err := models.DB.Where("ID=?", id).Create(&news)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
